package com.platform.qujia.rocketmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.platform.qujia.dao.SettleInfoRecordMapper;
import com.platform.qujia.pojo.SaasOrderBo;
import com.platform.qujia.pojo.SettleInfoSendRecord;
import com.platform.qujia.utils.StringUtils;
import com.platform.qujia.utils.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
import org.apache.rocketmq.spring.core.RocketMQTemplate;

import javax.annotation.Resource;


@Component
@Slf4j
public class SettleInfoProducer {
    @Value("${rocketmq.name-server}")
    private String nameServer;

    @Value("${rocketmq.producer.group}")
    private String producerGroup;

    @Value("${rocketmq.producer.tag}")
    private String tag;

    @Value("${rocketmq.producer.topic}")
    private String topic;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private SettleInfoRecordMapper settleInfoRecordMapper;


    public void sendMessage(SaasOrderBo saasOrderBo) {
        String saasOrderBoString = com.alibaba.fastjson.JSONObject.toJSONString(saasOrderBo);

        SettleInfoSendRecord settleInfoSendRecord = new SettleInfoSendRecord();
        settleInfoSendRecord.setOrderNo(saasOrderBo.getPayOrder());
        settleInfoSendRecord.setContent(saasOrderBoString);
        settleInfoSendRecord.setType(0);
        try {
//            Message<String> message1 = MessageBuilder.withPayload(message)
//                    .setHeader("KEYS", "123123")
//                    .build();
            log.info("推送的消息{}",saasOrderBoString);
            if(StringUtils.isBlank(saasOrderBo.getClearAccount()) || StringUtils.isBlank(saasOrderBo.getClearMerNo())){
                return;
            }
            SendResult sendResult = rocketMQTemplate.syncSend(topic + ":" + tag,saasOrderBoString,3000);
            log.info("清分信息发送结果{}", sendResult);
            if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
                settleInfoSendRecord.setStatus(1);
            } else {
                settleInfoSendRecord.setStatus(0);
            }
            settleInfoRecordMapper.insertSettleInfoRecord(settleInfoSendRecord);
        }catch (Exception e){
            settleInfoSendRecord.setStatus(0);
            settleInfoRecordMapper.insertSettleInfoRecord(settleInfoSendRecord);
            throw new CustomException("发送清分消息出现异常",e);
        }


    }
}
